{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 类的命名空间\n",
    "\n",
    "在class语句中定义的代码都是在一个特殊的命名空间（ **类的命名空间**）内执行的，而类的所有成员都可访问这个命名空间。类定义其实就是要执行的代码段，并非所有的Python程序员都知道这一点，但知道这一点很有帮助。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Class MemberCounter being defined ...\n",
      "MemberCounter.members:  1\n",
      "MemberCounter.members:  2\n",
      "m2.members:  2\n",
      "m1.members:  2\n",
      "m2.members:  Two\n",
      "MemberCounter.members:  2\n"
     ]
    }
   ],
   "source": [
    "class MemberCounter():\n",
    "    print('Class MemberCounter being defined ...')\n",
    "    members = 0 # 相当于这个命名空间的全局变量\n",
    "    def __init__(self):\n",
    "        MemberCounter.members += 1\n",
    "        \n",
    "m1 = MemberCounter()\n",
    "print(\"MemberCounter.members: \", MemberCounter.members) # 访问类中全局变量\n",
    "m2 = MemberCounter()\n",
    "print(\"MemberCounter.members: \", MemberCounter.members) # 访问类中全局变量\n",
    "print(\"m2.members: \", m2.members) # 访问全局变量\n",
    "m2.members = 'Two' # 给实例m2动态绑定重名属性\n",
    "print(\"m1.members: \", m1.members)\n",
    "print(\"m2.members: \", m2.members)\n",
    "print(\"MemberCounter.members: \", MemberCounter.members)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
